/**
 * Created by shenc on 2016/4/19.
 * 后台添加优惠券
 */

//根据类型生成checkbox
coupon();
function coupon(){

    var urlArr={
        1:'',
        2:'',
        3:'/admin/category/1',
        4:'/admin/shop/1',
        5:'/admin/brand/1'
    };

    var proType = $('#J-proType');
    var selWrap=$('.J-selWrap');
    var goodsWrap=$('.J-resultList');
    var sel2=$('.J-sel2',selWrap);
    var label=$('.J-label',selWrap);
    var selectResult=$('#selectResult');

    var selValues=(sel2.data('selected')+'')||'';//初始化  分类、店铺、品牌 的数据
    var oldType=sel2.data('type')-0||'';//初始化 类型的value

    selValues=selValues.length&&selValues.split(',');

    proType.on('change', function () {
        var id = proType.val()-0,
            url=urlArr[id],
            onLoading=$('.J-onLoading');

        if(id==1){
            //goodsWrap.removeClass('hide');
            goodsWrap.addClass('hide');
        }
        if(id==2){
            goodsWrap.removeClass('hide');
        }

        if(id==3){
            label.text('选择分类');
        }
        if(id==4){
            label.text('选择店铺');
        }

        if(id==5){
            label.text('选择品牌');
        }


        if(id==1||id==2){
            selWrap.addClass('hide');
        }else{
            goodsWrap.addClass('hide');
            //获取属性数据
            onLoading.removeClass('hide');
            $.ajax({
                url:url,
                type:'get',
                dataType:'json',
                data:{},
                success:function(res){
                    //console.log('oldType:',oldType,selValues);
                    if (typeof res == 'undefined'){
                        alert('链接服务器出错，请刷新重试！');
                    }


                    var options=[];

                    switch (id){
                        case 3://分类
                            for(var i=0;i<res.length;i++){
                                if(oldType==3&&selValues.length>0&&selValues.indexOf(res[i].cat_id+'')!=-1){
                                    options.push('<option selected value="'+res[i].cat_id+'">'+res[i].cat_name+'</option>')

                                }else{
                                    options.push('<option value="'+res[i].cat_id+'">'+res[i].cat_name+'</option>')
                                }
                            }
                            break;
                        case 4://店铺
                            for(var i=0;i<res.length;i++){

                                if(oldType==4&&selValues.length>0&&selValues.indexOf(res[i].id+'')!=-1){
                                    options.push('<option selected value="'+res[i].id+'">'+res[i].shop_name+'</option>')

                                }else{
                                    options.push('<option value="'+res[i].id+'">'+res[i].shop_name+'</option>')
                                }
                            }
                            break;
                        case 5://品牌
                            for(var i=0;i<res.length;i++){
                                console.log(selValues.indexOf(res[i].brand_id+''));
                                if(oldType==5&&selValues.length>0&&selValues.indexOf(res[i].brand_id+'')!=-1){
                                    options.push('<option selected value="'+res[i].brand_id+'">'+res[i].brand_name+'</option>')

                                }else{
                                    options.push('<option value="'+res[i].brand_id+'">'+res[i].brand_name+'</option>')
                                }
                            }
                            break;
                    }

                    sel2.html(options.join(""));
                    selWrap.removeClass('hide');

                    sel2.select2();

                    //监听select2 赋值selectResult
                    sel2.on('change',function(){
                        console.log('value:',sel2.select2("val"));
                        selectResult.val(sel2.select2("val").join());
                    });


                }
            }).then(function(){
                onLoading.addClass('hide');
            });


        }


    });
    proType.trigger('change');//触发初始化

    //商品弹出框出现时执行
    var goodsModal=$('#GoodsModal');
    var tbody=goodsWrap.find('tbody');
    var goodsInput=selectResult;

    var data={ids:[],names:{},trs:{}};
    var ids=goodsInput.val();
    if(ids!=""){
        data.ids=ids.split(',');
        for(var i=0;i<data.ids.length;i++){
            var curId=data.ids[i];
            var curTr=$('#selGoods-'+curId);

            data.names[curId]=curTr.find('.J-linkG').text();
            data.trs[curId]=curTr;
        }
    }
//console.log(data);

    var goodsList=new SearchGoods({
        selectedInput:selectResult,
        jqP:'#GoodsModal',
        okCb:function(ids,trs,obj){
            //console.log(arguments);
            goodsInput.val(ids.join());
            tbody.html("");
            for(var i=0;i<trs.length;i++){
                var tr=trs[i].tr;
                tr.find('.checkbox-wrap').remove();
                tr.attr('id','selGoods-'+tr.data('id'));
                tbody.append(tr);
            }

            goodsModal.modal('hide');
            goodsWrap.find('.goods-list').removeClass('hide');
        }
    });


    goodsModal.on('shown.bs.modal', function () {
        goodsList.init(data);
    });

}


//搜索商品
function SearchGoods(opts){
    var def={
        jqP:'',
        trTpl:$('#goodsTrTpl').html(),
        okCb:function(){}
    };

    this.config= $.extend({},def,opts||{});

    var This=this;
    var jqP=$(this.config.jqP);

    var searchForm=$('.J-search',jqP);
    var goodsWrap=$('.J-goodsList',jqP);
    var pageWrap=$('.J-page',jqP);
    var footer=$('.J-footer',jqP);
    var selected=$('.J-result',jqP);
    var loading=$('.J-loading',jqP);

    var url=searchForm.attr('action');
    var query='';
    var selGoods={};
    var selGoodsId=[];
    var selTrs=[];

    this._e={
        toggleTr:function(tr,notToggle){
            var id=tr.data('id');
            var checkbox=tr.find('.J-check');

            if(typeof notToggle =='undefined'||!notToggle){
                checkbox.prop('checked',!checkbox.prop('checked'));
            }

            if(checkbox.prop('checked')&&typeof selGoods[id] == 'undefined'){
                var name=tr.find('.J-linkG').text();
                var sel='<span id="label-'+id+'" class="label label-primary" style="margin:0 10px 10px 0;display: inline-block;*display:inline;zoom:1;">'+name+' <i style="cursor: pointer" data-id="'+id+'" class="J-del glyphicon glyphicon-remove"></i></span>';
                selected.append(sel);

                selGoods[id]={
                    tr:tr.clone()
                };
            }else if(!checkbox.prop('checked')){
                var curSel=selected.find('#label-'+id);
                curSel.length&&curSel.remove();
                delete selGoods[id];
            }

            footer.toggleClass('hide',$.isEmptyObject(selGoods));


        }
    };

    this.bind=function(){

        //点击商品名称
        jqP.on('click','.J-linkG',function(e){
            e.stopPropagation();//禁止冒泡
            window.open(this.href);//手动跳转页面
        });

        //点击checkbox
        jqP.on('click','.J-check',function(e){
            e.stopPropagation();//禁止冒泡
            This._e.toggleTr($(this).closest('tr'),true);
        });


        //选择事件
        jqP.on('click','.J-tr',function(){
            This._e.toggleTr($(this));
        });

        //删除按钮
        jqP.on('click','.J-del',function(){
            var that=$(this),
                id=that.data('id');
            var tr=$('#goods-list-tr'+id,jqP);
            //console.log('tr',tr);
            if(tr.length){
                This._e.toggleTr(tr);
            }else{
                delete selGoods[id];
                that.closest('.label').remove();
            }
        });

        //确定
        jqP.on('click','.J-ok',function(){
            selGoodsId=[];
            selTrs=[];

            for(var p in selGoods){
                if(selGoods.hasOwnProperty(p)){
                    selGoodsId.push(p);
                    selTrs.push(selGoods[p]);
                }
            }

            //回掉
            This.config.okCb(selGoodsId,selTrs,selGoods);
        });


        //查询按钮
        jqP.on('click','.J-searchBtn',function(e){
            e.preventDefault();//禁止
            query=This.makeQuery();
            This.getData();

            return false;//防止时间冒泡
        });


        //换页
        jqP.on('click','.J-page a',function(){
            var page=$(this).data('page');

            query=This.makeQuery()+'&page='+page;

            This.getData();

            return false;
        });


    };

    this.getData=function(){
        loading.removeClass('hide');

        //todo 正式环境删除
        //var url='/js/goods.json';
        $.ajax({
            url:url+'?'+query,
            type:'get',
            dataType:'json',
            data:{},
            success:function(res){
                //console.log(res);
                var trsHtml= This.makeHtml(res.data);
                var pageHtml = This.pager(res);

                if(trsHtml.length>0){
                    goodsWrap.html(trsHtml.join(""));
                }else{
                    goodsWrap.html("");
                }

                if(pageHtml&&pageHtml.length>3){
                    pageWrap.find('.pagination').html(pageHtml.join(''));
                }else{
                    pageWrap.find('.pagination').html('');
                }

                loading.addClass('hide');
            },
            error:function(){

            }

        })
    };

    this.makeQuery=function(){
        return searchForm.serialize();
    };

    this.makeHtml=function(data){
        var trs=[];
        var tr=This.config.trTpl;
        //商品类型，0：一般商品，1：e贸易商品
        var type=['一般商品','e贸易商品'];
        //核审状态：0：未审核；1：审核通过；2：审核不通过
        var audit_status=['未审核','审核通过','审核不通过'];
        //是否上架，1：上架；2：下架
        var is_on_sale=['','上架','下架'];

        for(var i=0;i<data.length;i++){
            var curData=data[i];
            //处理数据
            curData.is_checked=typeof selGoods[curData.goods_id] == 'undefined'?'data-a':'checked';
            curData.audit_class=curData.audit_status==1?'success':'warning';
            curData.sale_class=curData.is_on_sale==1?'success':'warning';

            curData.type=type[curData.type];
            curData.audit_status=audit_status[curData.audit_status];
            curData.is_on_sale=is_on_sale[curData.is_on_sale];

            trs.push(tools.htmlTemplate(tr,curData));
        }

        return trs;
    };

    this.pager=function(data){
        var pageHtml=[];

        //上一页
        if(data.current_page==1){
            pageHtml.push('<li class="disabled"><span>«</span></li>');
        }else{
            pageHtml.push('<li><a data-page="'+(data.current_page-1)+'" title="next">«</a></li>');
        }

        //中间页面
        if(data.last_page<=10){
            for(var i=1;i<=data.last_page;i++){
                if(i==data.current_page){
                    pageHtml.push('<li class="active"><span>'+i+'</span></li>');

                }else{
                    pageHtml.push('<li><a data-page="'+i+'">'+i+'</a></li>');

                }
            }
        }else{
            if(data.current_page<=6){
                for(var i=1;i<=8;i++){

                    if(i==data.current_page){
                        pageHtml.push('<li class="active"><span>'+i+'</span></li>');

                    }else{
                        pageHtml.push('<li><a href="javascript:;" data-page="'+i+'">'+i+'</a></li>');

                    }
                }
                pageHtml.push('<li class="disabled"><span>...</span></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="'+(data.last_page-1)+'">'+(data.last_page-1)+'</a></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="'+data.last_page+'">'+data.last_page+'</a></li>');
            }else if(data.last_page-data.current_page<=6){
                pageHtml.push('<li><a href="javascript:;" data-page="1">1</a></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="2">2</a></li>');
                pageHtml.push('<li class="disabled"><span>...</span></li>');

                for(var i=data.last_page-8;i<=data.last_page;i++){

                    if(i==data.current_page){
                        pageHtml.push('<li class="active"><span>'+i+'</span></li>');

                    }else{
                        pageHtml.push('<li><a href="javascript:;" data-page="'+i+'">'+i+'</a></li>');

                    }
                }
            }else{
                pageHtml.push('<li><a href="javascript:;" data-page="1">1</a></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="2">2</a></li>');
                pageHtml.push('<li class="disabled"><span>...</span></li>');

                for(var i=data.current_page-2;i<=data.current_page+2;i++){

                    if(i==data.current_page){
                        pageHtml.push('<li class="active"><span>'+i+'</span></li>');

                    }else{
                        pageHtml.push('<li><a href="javascript:;" data-page="'+i+'">'+i+'</a></li>');

                    }
                }

                pageHtml.push('<li class="disabled"><span>...</span></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="'+(data.last_page-1)+'">'+(data.last_page-1)+'</a></li>');
                pageHtml.push('<li><a href="javascript:;" data-page="'+data.last_page+'">'+data.last_page+'</a></li>');
            }
        }


        //下一页
        if(data.current_page==data.last_page){
            pageHtml.push('<li class="disabled"><span>»</span></li>');
        }else{
            pageHtml.push('<li><a href="javascript:;" data-page="'+(data.current_page+1)+'" title="next">»</a></li>');
        }


        return pageHtml;

    };

    this.init=function(options){
        var instance=This.getInstance();
        if(typeof instance !=='undefined') return false;
        //console.log('init');

        //初始化select
        $('.J-select',searchForm).select2();

        query=This.makeQuery();
        //console.log(query);

        //todo 带数据初始化
        if(typeof options !='undefined'&&options.ids.length>0){
            This.initWithData(options);
            //console.log('带数据初始化');
        }

        This.getData();

        This.bind();

        This.setInstance(This);
    };


    this.getInstance=function(){
        return $(This).data('instance');
    };
    this.setInstance=function(instance){
        $(This).data('instance',instance);
    };

    //带数据初始化
    this.initWithData=function(data){
        for(var i=0;i<data.ids.length;i++){
            var id=data.ids[i],name=data.names[id];
            var sel='<span id="label-'+id+'" class="label label-primary" style="margin:0 10px 10px 0;display: inline-block;*display:inline;zoom:1;">'+name+' <i style="cursor: pointer" data-id="'+id+'" class="J-del glyphicon glyphicon-remove"></i></span>';
            selected.append(sel);
            selGoods[id]={
                tr:data.trs[id]
            };
        }
        footer.removeClass('hide');
    };
}
